<script setup lang="ts">
import { ElButton, ElMessageBox, ElMessage } from "element-plus"
import { defineEmits, reactive, watchEffect, toRaw, computed } from 'vue';
import { getTypeName, questionTypeOptions, RADIO, CHECKBOX, TRUE_FALSE, FILL_BLANK, ESSAY } from "../const"
import dayjs from 'dayjs';
import { useQuestionItem } from "./question-hook"
import { ChevronsDownUp, Pencil, Trash2, ChevronsUpDown } from '@vben/icons';
import { debounceFn } from "#/utils/debounce"
import { cloneDeep } from "@vben/utils";
import { $t } from '@vben/locales';
import { COURSE_STATUS_MAP } from "#/types/const"
import { useMessageBox } from "#/hooks/useMessageBox";

const { confirm } = useMessageBox()

interface QuestionOption {
  name: string;
  conent: string;
}

type QuestionType = 'radio' | 'checkbox' | 'trueFalse' | 'fillBlank' | 'essay' | 'composite';

interface QuestionItem {
  id: string;
  type: QuestionType;
  stem: string;
  stemImg?: string;
  options: string | QuestionOption[];
  answers: string | string[];
  analysis: string;
  createTime: string;
  isHider?: boolean;
  courseStatus: string;
  courseName: string;
  chapterName: string;
}

defineOptions({ name: 'CardItem' })

const question = useQuestionItem()
const emit = defineEmits<{
  (e: 'del', id: string): void;
  (e: 'editQuestion', question: QuestionItem): void;
}>();

const props = defineProps({
  item: {
    type: Object as () => QuestionItem,
    required: true
  },
  indexNumber: {
    type: Number,
    default: 0
  },
  searchKeyword: {
    type: String,
    default: ''
  }
})

const rowIndex = computed(() => props.indexNumber + 1)

const formattedCreateTime = computed(() =>
  dayjs(props.item.createTime).format('YYYY-MM-DD HH:mm:ss')
)

const typeLabel = computed(() => {
  const found = questionTypeOptions.find(f => f.value === props.item.type)
  return found?.label || ''
})

const typeStyles = computed(() => {
  const { type } = props.item

  const styleMap: Record<QuestionType, { backgroundColor: string; color: string }> = {
    [RADIO]: { backgroundColor: '#DAEAFF', color: '#1677FF' }, // 单选题
    [CHECKBOX]: { backgroundColor: '#DCF3D1', color: '#41A80F' }, // 多选题
    [TRUE_FALSE]: { backgroundColor: '#D0F3F3', color: '#1CA9A9' }, // 判断题
    [FILL_BLANK]: { backgroundColor: '#EADFF9', color: '#9254DE' }, // 填空题
    [ESSAY]: { backgroundColor: '#FFEED9', color: '#D9851F' }, // 问答题
    composite: { backgroundColor: '#DAEAFF', color: '#1677FF' } // 复合题，默认样式
  }

  return styleMap[type] || { backgroundColor: '#DAEAFF', color: '#1677FF' }
})

const formattedAnswers = computed(() => {
  const { type, answers } = props.item

  if ([RADIO, TRUE_FALSE, CHECKBOX].includes(type)) {
    const answersData = JSON.parse(answers as string || '[]')
    if (Array.isArray(answersData)) {
      return answersData.map((item: any) => item.name).join(', ')
    } else {
      return answersData.name
    }
  }

  // if (type === CHECKBOX) {
  //   const answersData = JSON.parse(answers as string || '[]')
  //   return Array.isArray(answersData) ? answersData.join(', ') : answersData
  // }

  if (type === FILL_BLANK) {
    return Array.isArray(answers) ? answers.join(', ') : answers
  }

  return answers
})

const parsedOptions = computed(() => {
  if (!props.item.options) return []
  return typeof props.item.options === 'string'
    ? JSON.parse(props.item.options)
    : props.item.options
})

const onDel = debounceFn((item: QuestionItem) => {
  confirm($t('questionBank.confirmDelete'), {
    confirmButtonText: $t('questionBank.confirm'),
    cancelButtonText: $t('common.cancelTxt'),
  }).then((res: any) => {
    emit('del', item.id)
  })
}, 200)

const onEdit = (row: QuestionItem) => {
  question.value = cloneDeep(row)
  emit('editQuestion', row)
}

const isChoiceQuestion = (type: QuestionType): type is 'radio' | 'checkbox' | 'trueFalse' => {
  return [RADIO, CHECKBOX, TRUE_FALSE].includes(type)
}

const isFillBlankQuestion = (type: QuestionType): type is 'fillBlank' => {
  return type === FILL_BLANK
}

// 高亮显示搜索关键词
const highlightedStem = computed(() => {
  if (!props.searchKeyword || !props.item.stem) {
    return props.item.stem
  }
  const keyword = props.searchKeyword.trim()
  if (!keyword) {
    return props.item.stem
  }
  // 使用正则表达式进行不区分大小写的全局匹配
  const regex = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi')
  return props.item.stem.replace(regex, '<span style="color: var(--el-color-primary); padding: 0 2px; border-radius: 2px; font-weight: 600;">$1</span>')
})

const courseStatus = computed(() => {
  return COURSE_STATUS_MAP[props.item.courseStatus as keyof typeof COURSE_STATUS_MAP]
})
</script>

<template>
  <div
    class="rounded-lg border border-gray-200 bg-white shadow-sm hover:shadow-md transition-shadow duration-300 mb-4 overflow-hidden">
    <!-- 操作栏 -->
    <div class="flex items-center justify-between bg-blue-50 border-b border-gray-200 px-4 h-[32px]">
      <div class="flex items-center space-x-4">
        <div class="px-2 py-[3px] rounded text-[12px] font-normal" :style="typeStyles">
          {{ typeLabel }}
        </div>
        <el-divider direction="vertical" class="divider" />
      </div>
      <div class="flex-1 px-2">
        <div class="flex w-full justify-between">
          <span class="text-gray-500 text-xs text-center">{{ $t('common.statusTxt') }} <span class="text-[#191919]">{{ courseStatus }}</span></span>
          <span class="text-gray-500 text-xs text-center">{{ $t('course.course') }} <span class="text-[#191919]">{{ item.courseName }}</span></span>
          <span class="text-gray-500 text-xs text-center">{{ $t('course.chapter') }} <span class="text-[#191919]">{{ item.chapterName }}</span></span>
          <span class="text-gray-500 text-xs text-center">{{ $t('questionBank.createTime') }} <span class="text-[#191919]">{{ formattedCreateTime }}</span></span>
        </div>
      </div>
      <div class="flex items-center space-x-3">
        <el-divider direction="vertical" class="divider" />
        <el-button link text @click="() => (item.isHider = !item.isHider)">
          <ChevronsDownUp :size="16" class="text-gray-500" v-if="item.isHider" />
          <ChevronsUpDown :size="16" class="text-gray-500" v-else />
        </el-button>
        <el-button link text @click="onEdit(item)">
          <Pencil :size="16" class="text-gray-500" />
        </el-button>
        <el-button link text @click="onDel(item)">
          <Trash2 :size="16" class="text-gray-500" />
        </el-button>
      </div>
    </div>

    <!-- 内容区 -->
    <div class="p-4">
      <!-- 题目 -->
      <div class="flex  mb-4 items-center">
        <div class="text-sm font-medium text-gray-700">{{ rowIndex }}、</div>
        <div class="flex-1 text-base font-medium" v-html="highlightedStem"></div>
      </div>

      <div class="pl-5 text-[12px]" v-if="item.isHider">
        <!-- 题目选项 -->
        <div v-if="isChoiceQuestion(item.type)" class="mb-3">
          <div class="flex items-start">
            <span class="title">{{ $t('questionBank.questionOptions') }}</span>
            <div class="flex-1 space-y-2">
              <div v-for="option in parsedOptions" :key="option.name" class="flex items-start">
                <span class="text-content">{{ option.name }}{{ item.type === TRUE_FALSE ? '' : '、' }}</span>
                <span class="text-content">{{ option.content }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- <div v-if="isFillBlankQuestion(item.type)" class="mb-3">
          <div class="flex items-start">
            <span class="title">{{ $t('questionBank.questionOptions') }}</span>
            <div class="flex-1 grid grid-cols-1 gap-2 text-content">
              <span v-for="answer in item.answers" :key="answer" class="min-w-[120px] text-content">
                {{ answer }}
              </span>
            </div>
          </div>
        </div> -->

        <!-- 参考答案 -->
        <div class="mb-3">
          <div class="flex items-center min-h-[15px]">
            <span class="title flex-shrink-0">{{ $t('questionBank.referenceAnswer') }}</span>
            <span class="flex-1 text-gray-800 text-content" style="transform: translateY(-2px);"
              v-html="formattedAnswers"></span>
          </div>
        </div>

        <!-- 题目解析 -->
        <div class="mb-3">
          <div class="flex items-start">
            <span class="title">{{ $t('questionBank.questionAnalysis') }}</span>
            <div class="flex-1 text-gray-800 text-content" v-html="item.analysis"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.text-content {
  color: #191919 !important;
  font-weight: 400;
}

.title {
  color: #595959;
  display: inline;
  width: 70px;
}
</style>
